<script lang="ts" setup>
import { ref, toRaw } from "vue";
import TaskCreateDialog from "./TaskCreateDialog.vue";
import { addTask, clearAllTask, clearByTaskId, listTask } from "../api/task";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { BuildTaskRecord, WsMsgType } from "../model";
import { useWs } from "../utils/ws";

const visible = ref(false);
const loading = ref(false);
const searchText = ref("");
const taskList = ref<Partial<BuildTaskRecord>[]>([]);
const currentRow = ref<Partial<BuildTaskRecord>>();
const copyRow = ref<Partial<BuildTaskRecord>>();
const emit = defineEmits(["onChecked"]);

const handleCreateClick = () => {
  copyRow.value = undefined;
  visible.value = true;
};

const handleCopy = (row: any) => {
  copyRow.value = row;
  visible.value = true;
};

const afterCheckChanged = (item?: Partial<BuildTaskRecord>) => {
  if (!item) {
    emit("onChecked", null);
    return;
  }
  if (
    currentRow.value?.taskId !== item?.taskId ||
    currentRow.value?.status !== item?.status
  ) {
    emit("onChecked", toRaw(item));
  }
};

const handleCurrentChange = (row: Partial<BuildTaskRecord>) => {
  afterCheckChanged(row);
  currentRow.value = row;
};

const refreshList = () => {
  listTask({
    taskTitle: searchText.value,
  })
    .then((res) => {
      taskList.value = res;
      if (currentRow.value) {
        const item = taskList.value.find(
          (v) => v.taskId === currentRow.value?.taskId
        );
        afterCheckChanged(item);
      }
    })
    .catch((e) => {
      console.error(e);
      ElMessage.error("查询任务出错");
    });
};

const handleOk = (param: Record<string, any>) => {
  if (loading.value) return;
  loading.value = true;
  addTask(param as any)
    .then(() => {
      ElMessage.success("任务添加成功");
      visible.value = false;
      refreshList();
    })
    .catch((err: Error) => {
      ElMessage.error(err.message);
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSearch = () => {
  refreshList();
};

const deleteRow = ({ taskId, taskTitle }: BuildTaskRecord) => {
  ElMessageBox.confirm(`确定删除【${taskTitle}】？`, {
    buttonSize: "small",
  })
    .then(() => {
      clearByTaskId(taskId)
        .then(() => {
          refreshList();
        })
        .catch((e: Error) => {
          ElMessage.error(e.message);
        });
    })
    .catch(() => {});
};

const clearAll = () => {
  ElMessageBox.confirm("确定清理？", {
    buttonSize: "small",
  })
    .then(() => {
      clearAllTask()
        .then(() => {
          refreshList();
        })
        .catch((e: Error) => {
          ElMessage.error(e.message);
        });
    })
    .catch(() => {});
};

useWs(WsMsgType.TASK_UPDATE, (data: BuildTaskRecord) => {
  refreshList();
});

handleSearch();
</script>

<template>
  <div class="content">
    <div class="flex">
      <span>
        <el-button size="small" type="primary" @click="handleCreateClick"
          >创建任务</el-button
        >

        <el-button size="small" @click="clearAll"> 清理全部 </el-button>
      </span>
      <span>
        <el-input
          size="small"
          placeholder="输入名称搜索"
          v-model="searchText"
          :suffix-icon="Search"
          @keydown.enter.stop.prevent="handleSearch"
        ></el-input>
      </span>
    </div>
    <el-table
      size="small"
      row-key="taskId"
      :data="taskList"
      :max-height="600"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column
        :min-width="120"
        label="任务名称"
        prop="taskTitle"
      ></el-table-column>
      <el-table-column
        :min-width="160"
        label="任务描述"
        prop="taskDesc"
      ></el-table-column>
      <el-table-column
        :width="100"
        :align="'center'"
        label="任务状态"
        prop="status"
      >
      </el-table-column>
      <el-table-column
        :width="90"
        :align="'center'"
        label="操作"
        prop="actions"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            link
            @click.stop.prevent="() => handleCopy(row)"
          >
            复制
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click.stop.prevent="() => deleteRow(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <TaskCreateDialog v-model:visible="visible" :data="copyRow" @ok="handleOk" />
</template>

<style lang="scss" scoped>
.content {
  padding: 0 24px 10px;
}
.flex {
  display: flex;
  justify-content: space-between;
  padding: 0 0 10px;
  box-sizing: border-box;
}
</style>
